﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using SmallProject.Models.CutstomeUI;
using Small.Util.Reflection;

namespace SmallProject.UserControls.Extension
{
    public static class HtmlCheckBoxs
    {

        /// <summary>
        /// CheckBox
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="name">名称</param>
        /// <param name="source">资源</param>
        /// <param name="selectValues">选中项,以逗号分隔的字符</param>
        /// <param name="htmlAttribute">Html属性</param>
        /// <returns></returns>
        public static MvcHtmlString CheckBoxList(this HtmlHelper helper, String name, IList<SelectItem> source, string selectValues, Object htmlAttribute = null) 
        {


            List<string> selectValueArray = new List<string>();
            if (selectValues != null)
            {
                selectValueArray = selectValues.Split(',').ToList();
            }
            StringBuilder builder = new StringBuilder();
            
            if (source != null)
            {
                if (selectValues != null) 
                {

                    var selectedItems = source.Where(p => selectValueArray.Contains(Convert.ToString(p.Value))).Select(p=>p);

                    if (selectedItems != null)
                    {
                        foreach (var item in selectedItems)
                        {

                            item.IsDefault = true;
                        }
                    }
                }

                var htmlAttributes = AnonymousProperties.GetAnonymousInfomation(htmlAttribute);



                foreach (var item in source)
                {
                    
                
                builder.Append("   <input type=\"checkbox\"  name=\"" + name+"\"");

                if (htmlAttributes != null)
                {
                    foreach (var item1 in htmlAttributes)
                    {

                        builder.Append("  " + item1.Name + "=\"" + item1.Value + "\"");
                    }
                }

                if (item.IsDefault) 
                {
                    builder.Append(" checked=\"checked\"");
                }

                builder.Append("  value=\"" + item.Value + "\"");

                    builder.Append("/>"+item.Text+"\r\n");

                }
              

            }

          

          return new MvcHtmlString(builder.ToString());
        
        }
  
    }
}